/*
 * Copyright (C) 2015 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mfhcd.facepay.converter;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.mfhcd.facepay.global.AppConfig;
import com.mfhcd.facepay.network.NetErrorException;
import com.mfhcd.facepay.utils.Constants;
import com.mfhcd.facepay.utils.LogUtil;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class ErrorGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private static final String TAG = "XJGJ_NET";
    private final TypeAdapter<T> adapter;
    private final Gson gson;

    ErrorGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            // 处理返回码
            String jsonStr = value.string();
            String responseCode = "";
            String responseMsg = "";
            try {
                JSONObject responseJsonObject = JSON.parseObject(jsonStr);
                // sass请求，message字段为字符串类型,转化不做处理
                // paas请求，message字段为json类型，先删除message字段，重新添加passMessage并赋值
                if (responseJsonObject.containsKey("code")) {
                    responseCode = responseJsonObject.getString("code");
                    responseMsg = responseJsonObject.getString("msg");
                    LogUtil.i("saas请求");
                } else if (responseJsonObject.containsKey("CPSCOD")) {
                    LogUtil.i("paas请求");
                    responseCode = responseJsonObject.getString("CPSCOD");
                    // 00:交易成功，转化为0000统一判断操作成功
                    if ("00".equals(responseCode)) {
                        responseCode = "0000";
                    }
                    responseMsg = responseJsonObject.getString("procDesc");
                    JSONObject messageObj = responseJsonObject.getJSONObject("message");
                    responseJsonObject.put("code", responseCode);
                    responseJsonObject.put("message", responseMsg);
                    responseJsonObject.put("data", messageObj);
                    jsonStr = responseJsonObject.toJSONString();
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (AppConfig.DEBUG) {
                    e.printStackTrace();
                }
                throw new NetErrorException("请求响应数据解析异常", NetErrorException.PARSE_ERROR);
            }
            if (!TextUtils.isEmpty(responseCode)) {
                //处理token失效
                if (Constants.TOKEN_INVALIDATE.equals(responseCode)) {
                    throw new NetErrorException(responseMsg, NetErrorException.TOKEN_INVALIDATE);
                } else if (!"0000".equals(responseCode)) {
                    throw new NetErrorException(responseMsg, responseCode);
                }
                return adapter.fromJson(jsonStr);
            } else {
                JsonReader jsonReader = gson.newJsonReader(value.charStream());
                T result = adapter.read(jsonReader);
                if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                    throw new JsonIOException("JSON document was not fully consumed.");
                }
                return result;
            }
        } catch (ClassCastException e) {
            if (AppConfig.DEBUG) {
                e.printStackTrace();
            }
            throw new NetErrorException("数据解析异常", NetErrorException.PARSE_ERROR);
        } finally {
            value.close();
        }
    }
}
